<template>
  <div class="map-view" id="map-box-id">
  </div>
  <div class="popup-info" :style="{top:top,left:left}">我是问题</div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { Button,Popup,Picker,Icon} from 'vant';
import { getList } from '@/utils/duobian';
import * as turf from '@turf/turf';

import mapboxgl from 'mapbox-gl'
const mapboxtoken ="pk.eyJ1IjoiYnJpdHRhbnl5ZWUiLCJhIjoiY2p1ZTdpN3M4MDBlMzQ0bHJhaDh1b203ZyJ9.Kv9ykdRmPx5utrcMAY9uCg";
const tdttoken = "4cc66d27a3ef65764e7a58096e89aaf2";

let map:any= null

const top:any =ref(0)
const left:any =ref(0)

const lng:any =ref(0)
const lat:any =ref(0)

onMounted(async ()=>{
  mapboxgl.accessToken = mapboxtoken; // 替换为你的Mapbox access token
  let dataList = getList()
   console.log(dataList,'===========dataList')
    map = new mapboxgl.Map({
    container: 'map-box-id',
      center: [106.14657125, 29.88126174],
      zoom: 12,
      style: "mapbox://styles/mapbox/satellite-v9",
       pitch: 45, // 地图倾斜角度
       bearing: -17.6, // 地图旋转角度
    });
    // var polygons = dataList.map((item:any)=>item.geometry.coordinates)
 //跳转代码
// map.jumpTo({
// center: [0, 0],
// zoom: 8,
// pitch: 45,
// bearing: 90
// });
// //飞到代码
// map.flyTo({
// center: [0, 0],
// zoom: 9,
// speed: 0.2,
// curve: 1,
// easing(t) {
// return t;
// }
// }); 

    // WMTS图层样式
    let geoserverLayerStyle:any = {
        "id": "geoserver-wmts",
        "type": "raster",
        "source": {
            "type": "raster",
            "tiles": [
                "https://geo.cqtancheng.com/gwc/service/wmts?" +
                "REQUEST=GetTile&VERSION=1.0.0&LAYER=layerGroups&STYLE=default&Format=image/png" +
                "&TILEMATRIXSET=WebMercatorQuad&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}"
            ],
            "tileSize": 256
        },
        "minzoom": 0,
        "maxzoom": 22
    };

    map.on('load', function() {
// 假设有一个地理坐标点

    //  const tdt_url ="https://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=";

    //   map.addSource("tdt-source", {
    //     type: "raster",
    //     tiles: [tdt_url + tdttoken],
    //     tileSize: 256,
    //   });
    //   map.addLayer({
    //     id: "tdt-layer",
    //     type: "raster",
    //     source: "tdt-source",
    //   });

  map.setLayoutProperty('poi-label', 'visibility', 'none');

     // 添加天地图的 cia_w 图层
        map.addSource('cia_w', {
            type: 'raster',
            tiles: ['https://t0.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk='+tdttoken],
            tileSize: 256
        });
        map.addLayer({
            id: 'cia_w-layer',
            type: 'raster',
            source: 'cia_w',
            minzoom: 0,
            maxzoom: 22
        });
    //  map.addLayer(geoserverLayerStyle);

    // 添加多边形数据源
    map.addSource('polygons-source', {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: dataList.map((item, index)=> {
                return {
                    type: 'Feature',
                    id:item.properties.farmlandid,
                    properties: {
                        description: item.properties.landname+'\n'+Number(item.properties.mapareasize||0).toFixed(2)+'亩',
                        lineColor:'#25c289',
                        lineWidth:2,
                        ...item.properties
                    },
                    geometry: {
                        type: 'Polygon',
                        coordinates: item.geometry.coordinates
                    }
                };
            })
        }
    });
 
    // 添加多边形图层-线条
    map.addLayer({
        'id': 'polygons-layer-line',
        'type': 'line',
        'source': 'polygons-source',
        'layout': {},
        'paint': {
            // 'fill-color': 'rgba(255, 255, 255, 0)', // 背景色 颜色
            // 'fill-opacity': 0, // 背景色填充透明度、
            // 'fill-outline-color':'#25c289', // 设置边框颜色为红色
            // 'fill-opacity':1, // 设置边框的透明度
            // 'fill-outline-width': 5, // 设置边框宽度为5
            //  "line-color": "#25c289", //边框
             'line-color': ['get', 'lineColor'],
            'line-width': ['get', 'lineWidth'],

        }
    });
 // 添加多边形图层-图层
    map.addLayer({
        'id': 'polygons-layer-fill',
        'type': 'fill',
        'source': 'polygons-source',
        'paint': {
            // 'fill-color': 'rgba(255, 255, 255, 0)', // 背景色 颜色
            'fill-opacity': 0, // 背景色填充透明度、
            // 'fill-outline-color':'#25c289', // 设置边框颜色为红色
            // 'fill-opacity':1, // 设置边框的透明度
            //  "line-color": "#25c289", //边框
            // 'line-width': 2, // 设置边框宽度为5
            'fill-color': [
                'case',
                ['feature-state', 'click'],
                '#ff0000', // 点击后的颜色
                '#0080ff'  // 默认颜色
              ],
          }
    });

    // 添加多边形图层-文字
    map.addLayer({
        'id': 'polygons-layer-text',
        'type': 'symbol',
        'source': 'polygons-source',
         layout: {
            // 'text-field': '我是文字',
            'text-field': ['get', 'description'], // 这里假设GeoJSON有一个名为description的属性
            'text-size': 12,
            'text-anchor': 'center',
            'visibility': 'none',
            'text-offset': [0, 1.5],
        },
        paint: {
            'text-color': '#ffffff'
        },
        metadata: {
            'renderedOnServer': false
        },
    });



      map.on('click','polygons-layer-line',(e:any)=> {
        // e.features 包含了点击的多边形的特征
        console.log('============', e.features[0]);
      });

      map.on('drag', function(e) {
        // 获取拖动的坐标
        console.log(e.lngLat,'======1');
        const point = map.project(new mapboxgl.LngLat(Number(lng.value), Number(lat.value)));
          top.value=point.y+'px'
          left.value=point.x+'px'
      });

      map.on('dragend', function(e) {
         console.log(e.lngLat,'======1');
        const point = map.project(new mapboxgl.LngLat(Number(lng.value), Number(lat.value)));
          top.value=point.y+'px'
          left.value=point.x+'px'
      });

      map.on('zoom', function(e) {
   const point = map.project(new mapboxgl.LngLat(Number(lng.value), Number(lat.value)));
          top.value=point.y+'px'
          left.value=point.x+'px'
});

map.on('zoomend', function(e) {
     const point = map.project(new mapboxgl.LngLat(Number(lng.value), Number(lat.value)));
          top.value=point.y+'px'
          left.value=point.x+'px'
});
     map.on('click','polygons-layer-fill',(e:any)=> {
      // var featureId = e.features[0].id;

        // e.features 包含了点击的多边形的特征
        // map.setPaintProperty('polygons-layer-fill', 'fill-color', '#25c289');
        // map.setPaintProperty('polygons-layer-fill', 'fill-opacity', 0.8);
          // var featureId = e.features[0].id;
          // console.log(featureId)
        let pont =e.features[0].properties
console.log(e.features[0].geometry.coordinates,'==========e.features[0].geometry.coordinates')
        getImage(e.features[0].geometry.coordinates)
        lng.value=Number(pont.locationlongitude)
        lat.value=Number(pont.locationlatitude)
        const point = map.project(new mapboxgl.LngLat(Number(pont.locationlongitude), Number(pont.locationlatitude)));
          top.value=point.y+'px'
          left.value=point.x+'px'



      });

       // 为多边形层添加鼠标悬停事件
    // map.on('mouseenter', 'polygons-layer-fill',(e:any)=> {
    //     // 当鼠标悬停时显示文本层
    //     map.setLayoutProperty('polygons-layer-text', 'visibility', 'visible');
    // });
 
    // map.on('mouseleave', 'polygons-layer-fill', (e:any)=> {
    //     // 当鼠标离开时隐藏文本层
    //     map.setLayoutProperty('polygons-layer-text', 'visibility', 'none');
    // });
 });
})


const getImage =(coordinates:any)=>{

 // 添加多边形图层
    map.addLayer({
        'id': 'polygon-layer',
        'type': 'fill',
        'source': {
            'type': 'geojson',
            'data': {
                'type': 'Feature',
                'properties': {},
                'geometry': {
                    'type': 'Polygon',
                    'coordinates': coordinates
                }
            }
        },
        'layout': {},
        'paint': {
            'fill-color': '#088',
            'fill-opacity': 0.8
        }
    });
 
    // 使用snapshot方法保存地图视图为图片
    map.snapshot({
        style: 'mapbox://styles/mapbox/streets-v110',
        center: map.getCenter(),
        zoom: map.getZoom(),
        width: 800,
        height: 600
    }).then(function(data) {
        // 创建一个图片元素并设置src属性为图片的DataURL
        var img = document.createElement('img');
        console.log(data.toDataURL())
        img.src = data.toDataURL();
        // 将图片添加到DOM中
        document.body.appendChild(img);
    });
}
</script>
<style lang="scss" scoped>
.map-view{
  height:100vh;
  width:100vw;
  position: relative;
  overflow: hidden;
}
.popup-info{
  position: absolute;
  z-index:999;
  border:1px solid red;
  background-color: #fff;
  font-size:15px;
  color: #333;
  width:100px;
  height:50px;
  text-align: center;
}
</style>
